package com.ma.chapter6.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.function.UnaryOperator;

public class UnsafeAccessor {
    static Unsafe unsafe;

    static {
        try {
            /*
             * Unsafe 对象提供了非常底层的，操作内存、线程的方法，Unsafe 对象不能直接调用，只能通过反射获得
             * */
            //通过反射拿到Unsafe类的私有字段
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            //设置允许访问私有成员变量
            theUnsafe.setAccessible(true);
            //拿到该静态成员变量
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static Unsafe getUnsafe() {
        return unsafe;
    }
}
